<template>
  <div :class="$style.paper">
    <div :class="$style.banner">
      <span :class="$style.bannerTitle">{{ paperData.title }}</span>
      <div :class="$style.bannerInfo">
        <span :class="$style.bannerTime">创建时间：{{ createTime }}</span>
        <span :class="$style.bannerNum">已填写：{{ paperData.fillNum }}</span>
      </div>
    </div>
    <paper-querstion-card
      v-for="item in showQuestionList"
      :id="`paper-question-${item.order}`"
      :key="item.id"
      :qid="item.id"
      :title="item.name"
      :order="String(item.order)"
      :options="item.option"
      :type="item.type"
      :sliderData="item.type === 6 && item.option[0] ? item.option[0].slip : {}"
      :value="item.value"
      @answer="getUserAnswer"
    />
    <!-- 底部操作栏 -->
    <div :class="$style['paper-button-position']"></div>
    <div :class="$style['paper-operate-warpper']">
      <div :class="$style['paper-answered-area']" @click="onClickPopupBottom">
        <span>已答</span>
        <span :class="$style['paper-compelete-number']">{{ answerLength }}</span> /
        <span>{{ showQuestionList.length }}</span>
      </div>
      <div :class="$style['paper-submit-button']" @click="onClickSubmit">提交问卷</div>
    </div>
    <!-- popup部分，弹出答题卡 -->
    <van-popup v-model="popupShow" round position="bottom">
      <div :class="$style['paper-answer-card']">
        <div
          v-for="item in showQuestionList"
          :key="item.order"
          :class="[
            $style['paper-answer-card-item'],
            item.isCompelete ? $style['paper-answer-card-item-compelete'] : '',
          ]"
          @click="onClickCardItem(item.order)"
        >
          {{ item.order }}
        </div>
      </div>
      <div :class="$style['paper-answer-cancel-popup']" @click="onClickCancelPopupButton">取消</div>
    </van-popup>
  </div>
</template>

<script>
import { GetSurveyDetail, SubmitSurvey } from '@/apis';
import { Popup, Toast } from 'vant';
import QuestionCard from '@/components/paper-question-card/paper-question-card';
import { dateFormat } from '@/helpers/data-transform';

export default {
  name: 'Paper',
  components: {
    'paper-querstion-card': QuestionCard,
    'van-popup': Popup,
  },
  data() {
    return {
      paperData: {},
      questionList: [],
      /** 用于存储用户的答案,也是提交后台的数据
       *{} 题目id questionId: string,答案 answerOption:[],是否完成 iscompelete: boolean
       */
      userAnswer: [],
      /** 用于控制popup是否弹出 */
      popupShow: false,
      showQuestionList: [],
    };
  },
  computed: {
    answerLength() {
      const CompeleteArray = this.showQuestionList.filter((item) => {
        return item.isCompelete;
      });
      return CompeleteArray.length;
    },
    createTime() {
      return dateFormat(
        'yyyy/MM/dd hh:mm',
        this.paperData.createTime ? new Date(this.paperData.createTime) : new Date(),
      );
    },
  },
  watch: {
    userAnswer(newUserAnswer) {
      /** 跳题逻辑处理 */
      let allQuestionList = this.questionList;
      allQuestionList.forEach((item) => {
        const skiplogic = item.skipLogic;

        skiplogic.forEach((skiplogicItem) => {
          const useAnswer = newUserAnswer.find((answerItem) => {
            return answerItem.questionId === item.id;
          });

          /** 判断是否满足跳题条件 */
          let isSkip = true;
          /** 改题目是否已经被作为跳题处理,即在allQuestionList中该题目已经不存在 */
          const findItem = allQuestionList.find((showItem) => {
            return showItem.id === item.id;
          });

          /** 不存在则不需要跳题 */
          if (!findItem) {
            isSkip = false;
          }

          /** 用户回答的内容是否与跳题的条件匹配 */
          if (useAnswer?.answerOption?.length === skiplogicItem.option.length) {
            skiplogicItem.option.forEach((optionItem) => {
              if (useAnswer.answerOption.indexOf(optionItem) === -1) {
                isSkip = false;
              }
            });
          } else {
            isSkip = false;
          }

          /** 提前结束类型 */
          if (isSkip && skiplogicItem.isEnd) {
            allQuestionList = allQuestionList.filter((questionItem) => {
              return questionItem.order <= item.order;
            });
          }

          /** 跳题类型 */
          if (isSkip && skiplogicItem.skipToQid) {
            const taget = allQuestionList.find((questionItem) => {
              return questionItem.qid === skiplogicItem.skipToQid;
            });
            allQuestionList = allQuestionList.filter((questionItem) => {
              return questionItem.order >= taget.order || questionItem.order <= item.order;
            });
          }
        });
      });

      this.showQuestionList = [...allQuestionList];
    },
  },
  mounted() {
    const paperId = this.$router.history.current.query?.id;
    if (paperId) {
      const toastLoading = Toast.loading({
        message: '加载中...',
        duration: 0,
      });
      GetSurveyDetail(paperId).then(({ data }) => {
        toastLoading.clear();
        this.paperData = data;
        this.questionList = data.question.map((item, i) => {
          return {
            ...item,
            order: i + 1,
          };
        });
        this.showQuestionList = JSON.parse(JSON.stringify(this.questionList));
      });
    }
  },
  methods: {
    getUserAnswer(answer, compelete, id) {
      let constructAnswer = answer;
      /** 对answer进行改造，必须是数组，并且，数组元素必须是字符串 */
      if (!Array.isArray(answer)) {
        constructAnswer = [String(answer)];
      }

      /** 改变questionList 的value值和isCompelete的值，用于回填 */
      this.questionList.forEach((item) => {
        if (item.id === id) {
          item.value = constructAnswer;
          item.isCompelete = compelete;
        }
      });

      /** userAnswer是否已经存在 */
      const targetIndex = this.userAnswer.findIndex((item) => {
        return item.questionId === id;
      });

      if (targetIndex !== -1) {
        this.$set(this.userAnswer, targetIndex, {
          questionId: id,
          answerOption: constructAnswer,
          isCompelete: compelete,
        });
      } else {
        this.userAnswer.push({
          questionId: id,
          answerOption: constructAnswer,
          isCompelete: compelete,
        });
      }
    },
    /** 点击popup从底部弹出 */
    onClickPopupBottom() {
      this.popupShow = true;
    },
    /** 点击取消popup */
    onClickCancelPopupButton() {
      this.popupShow = false;
    },
    /** 点击提交问卷 */
    onClickSubmit() {
      /** 检测是否所有必答题目都已经完成 */
      let allIsCompelete = true;
      this.showQuestionList.forEach((item) => {
        if (item.mustFillIn) {
          item.isCompelete ? '' : (allIsCompelete = false);
        }
      });
      /** 如果全部必答题都已经完成就可以提交了 */
      const paperId = this.$router.history.current.query?.id;
      if (allIsCompelete && paperId) {
        const dataAnswer = [...this.userAnswer];
        const ToastLoading = Toast.loading({
          duration: 0,
          message: '提交中...',
        });
        SubmitSurvey(Number(paperId), {
          question: dataAnswer.filter((answerItem) => {
            let result = false;
            /** 需要过滤掉已经跳了的题目 */
            this.showQuestionList.forEach((showItem) => {
              showItem.id === answerItem.questionId ? (result = true) : '';
            });
            return result;
          }),
        }).then(() => {
          ToastLoading.clear();
          Toast.success({
            message: '问卷已提交',
          });
          this.$router.replace('/surveyList');
        });
      } else {
        Toast.fail({
          message: '请你先完成所有必答题',
        });
      }
    },
    /** 点击答题卡的小标题 */
    onClickCardItem(order) {
      const targetDom = document.getElementById(`paper-question-${order}`);
      const top = targetDom?.offsetTop;
      document.documentElement.scrollTop = top;
      document.body.scrollTop = top;
      this.popupShow = false;
    },
  },
};
</script>

<style lang="less" module>
@import '~vant/lib/style/var.less';
@import '~@scf/ding-style-less/var.less';
@import '../../global.less';

.paper {
  padding: 0 @padding-content;
}

.paper-button-position {
  height: 60px;
}

.paper-operate-warpper {
  height: 60px;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 10px 16px;
  box-shadow: 0px -4px 20px rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: space-between;
}

.paper-submit-button {
  background-color: @primary-color;
  width: 260px;
  height: 40px;
  border-radius: 20px;
  line-height: 40px;
  color: #fff;
  font-size: 14px;
  text-align: center;
  cursor: pointer;
}

.paper-answered-area {
  line-height: 40px;
}

.paper-answer-card {
  display: flex;
  flex-wrap: wrap;
}

.paper-answer-card-item {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  line-height: 40px;
  text-align: center;
  margin-left: 20px;
  margin-top: 20px;
  border: 1px solid @border-color;
  color: @button-color;
  font-size: 16px;
}

.paper-answer-card-item-compelete {
  background-color: @primary-color;
  border: 1px solid @primary-color;
  color: #fff;
}

.paper-answer-cancel-popup {
  width: 100%;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border-top: 1px solid @border-color;
  color: @button-color;
  margin-top: 30px;
  font-size: 16px;
  cursor: pointer;
}

.paper-compelete-number {
  color: @primary-color;
  margin-left: 10px;
}
.banner {
  display: flex;
  background: #fff;
  padding: 15px;
  flex-direction: column;
  border-radius: 6px;
  margin-top: 10px;
}
.bannerTitle {
  font-weight: 500;
  font-size: 14px;
  color: #303133;
  line-height: 24px;
  margin-bottom: 10px;
}
.bannerInfo {
  display: flex;
}
.bannerTime {
  flex-grow: 1;
  line-height: 20px;
  color: #909399;
}
.bannerNum {
  color: #606266;
  line-height: 20px;
}
</style>
